package leetcode;

import java.util.*;

public class LC2 {
    public static void main(String[] args) {
        LC2 lc1 = new LC2();
        System.out.println(lc1.groupAnagrams(new String[]{"eat","tea","tan","ate","nat","bat"}));
    }
    // 2024-11-20 回顾
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<Integer,List<Integer>> map = new HashMap<>();
        for (int i = 0; i < strs.length; i++) {
            int[] m = new int[26];
            for (int j = 0; j < strs[i].length(); j++) {
                m[strs[i].charAt(j) - 'a']++;
            }
            List<Integer> l = map.getOrDefault(Arrays.hashCode(m), new ArrayList<>());
            l.add(i);
            map.put(Arrays.hashCode(m),l);
        }
        List<List<String>> ans = new ArrayList<>();
        for (List<Integer> value : map.values()) {
            List<String> an = new ArrayList<>();
            for (Integer integer : value) {
                an.add(strs[integer]);
            }
            ans.add(an);
        }
        return ans;
    }

    public List<List<String>> groupAnagrams1(String[] strs) {
        List<List<String>> m = new ArrayList<>();
        for(int i = 0 ; i< strs.length; i++){
            String x = strs[i];
            for(int j = 0; j < m.size(); j++){
                String y = m.get(i).get(0);
                if(yw(x,y)){
                    System.out.print(m.get(i).get(0));
                    m.get(i).add(y);
                }
                else{
                    List<String> mm = new ArrayList<>();
                    mm.add(y);
                    m.add(mm);
                }
            }
        }
        return m;
    }
    public boolean yw(String a, String b){
        if(a.length() != b.length()) return false;
        int[] x = new int[b.length()];
        for(int i = 0; i< b.length(); i++){
            x[i] = (int)b.charAt(i);
        }
        for(int i = 0; i < a.length(); i++){
            boolean bool = false;
            for(int j = 0; j < x.length; j ++){
                if(a.charAt(i) == x[j]){
                    x[j] = -1;
                    bool = true;
                    break;
                }
            }
            if(!bool) return false;
        }
        return true;
    }
}
